package com.paipaideli.ui.profit;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding2.view.RxView;
import com.paipaideli.R;
import com.paipaideli.common.base.BasePresenterActivity;
import com.paipaideli.common.http.Api;
import com.paipaideli.common.pullrefresh.PullRefreshView;
import com.paipaideli.common.utils.DateUtil;
import com.paipaideli.common.utils.ImageUtil;
import com.paipaideli.common.utils.ToastUtil;
import com.paipaideli.ui.profit.bean.MentorBean;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by 师徒关系
 */
public class MentorActivity extends BasePresenterActivity {

    Unbinder unbinder;
    @BindView(R.id.top_back)
    RelativeLayout top_back;
    @BindView(R.id.top_title)
    TextView top_title;
    @BindView(R.id.mentor_recycleview)
    PullRefreshView mentor_recycleview;
    @BindView(R.id.tv_profit_jl)
    TextView tv_profit_jl;
    @BindView(R.id.tv_profit_wby)
    TextView tv_profit_wby;
    @BindView(R.id.tv_profit_yby)
    TextView tv_profit_yby;
    @BindView(R.id.image_mentor_head)
    ImageView imageMentorHead;
    @BindView(R.id.tv_mentor_username)
    TextView tvMentorUsername;
    @BindView(R.id.tv_mentor_parter)
    TextView tvMentorParter;
    @BindView(R.id.lin_mentor_stjl)
    LinearLayout linMentorStjl;
    @BindView(R.id.lin_mentor_wby)
    LinearLayout linMentorWby;
    @BindView(R.id.lin_mentor_yby)
    LinearLayout linMentorYby;

    private MentorAdapter mentorAdapter;
    private List<MentorBean.Data.PupilResList> list = new ArrayList<>();

    private int curPage = 1;
    private int total;
    private int pageSize;

    private String canExtracted = "";

    @Override
    public int getContentView() {
        return R.layout.activity_mentor;
    }

    @Override
    public void initView() {
        unbinder = ButterKnife.bind(this);
        top_title.setText("师徒");
        //返回
        top_back.setOnClickListener(o ->
                finish()
        );

        //第一个按钮点击
        RxView.clicks(linMentorStjl).subscribe(o -> {
            tv_profit_jl.setTextColor(this.getResources().getColor(R.color.red));
            tv_profit_wby.setTextColor(this.getResources().getColor(R.color.textview));
            tv_profit_yby.setTextColor(this.getResources().getColor(R.color.textview));
            list.clear();
            curPage = 1;
            canExtracted = "";
            initDate();
        }, throwable -> {
        });

        //第二个按钮点击
        RxView.clicks(linMentorWby).subscribe(o -> {
            tv_profit_jl.setTextColor(this.getResources().getColor(R.color.textview));
            tv_profit_wby.setTextColor(this.getResources().getColor(R.color.red));
            tv_profit_yby.setTextColor(this.getResources().getColor(R.color.textview));
            canExtracted = "0";
            list.clear();
            curPage = 1;
            initDate();
        }, throwable -> {
        });

        //第三个按钮点击
        RxView.clicks(linMentorYby).subscribe(o -> {
            tv_profit_jl.setTextColor(this.getResources().getColor(R.color.textview));
            tv_profit_wby.setTextColor(this.getResources().getColor(R.color.textview));
            tv_profit_yby.setTextColor(this.getResources().getColor(R.color.red));
            list.clear();
            curPage = 1;
            canExtracted = "1";
            initDate();
        }, throwable -> {
        });

        mentor_recycleview.setEnableRefresh(true);
        //设置是否在全部加载结束之后Footer跟随内容
        mentor_recycleview.setOnRefreshListener(refreshlayout -> {
            list.clear();
            curPage = 1;
            initDate();
            mentor_recycleview.finishRefresh();
        });

        mentor_recycleview.setLoadmoreListener(refreshlayout -> {
            double p = Math.ceil(Double.valueOf(total)/Double.valueOf(pageSize));
            int page = Integer.valueOf((int) p);
            if (curPage < page) {
                curPage++;
                initDate();
            } else {
                //加载完成 并且 标记为没有更多数据
                refreshlayout.finishLoadmoreWithNoMoreData();
            }
            mentor_recycleview.finishLoadmore();
        });
        mentorAdapter = new MentorAdapter();
        mentor_recycleview.setLayoutManager(new LinearLayoutManager(this));
        mentor_recycleview.setAdapter(mentorAdapter);

        mentor_recycleview.showLoading();
        initDate();
    }

    public void initDate() {
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("canExtracted", canExtracted);
            requestData.put("curPage", curPage);
            requestData.put("pageSize", "10");
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().pupil(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    if (request.code.equals("200")) {
                        ImageUtil.displayImage(request.data.avatar, imageMentorHead);
                        tvMentorUsername.setText(request.data.userName);
                        tvMentorParter.setText("师傅：" + request.data.parentUsername);
                        tv_profit_jl.setText("收徒记录(" + request.data.pupilCount + "人)");
                        tv_profit_wby.setText("未毕业(" + request.data.unGraduateCount + "人)");
                        tv_profit_yby.setText("已毕业(" + request.data.graduateCount + "人)");
                        list.addAll(request.data.pupilResList);
                        total = request.total;
                        curPage = request.curPage;
                        pageSize = request.pageSize;
                        mentorAdapter.notifyDataSetChanged();
                        mentor_recycleview.finishLoading();
                        ToastUtil.show(request.msg);
                    } else {
                        mentor_recycleview.showEmpty(request.msg);
                        ToastUtil.show(request.msg);
                    }
                }, throwable -> {
//                    mentor_recycleview.showError(throwable);
                    Log.e(TAG, "error", throwable);
                });
    }

    public class MentorAdapter extends RecyclerView.Adapter {

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(MentorActivity.this).inflate(R.layout.item_mentor_view, null);
            inflate.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            return new ViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            ViewHolder viewHolder = (ViewHolder) holder;
            viewHolder.tvMentorName.setText(list.get(position).userName);
            viewHolder.tvMentorTime.setText(DateUtil.getDateToString(list.get(position).createTime));
            viewHolder.tvMentorPrice.setText(list.get(position).acquirableMoney);
            if (list.get(position).extracted.equals("0")) {
                viewHolder.tvMentorPrice.setText(list.get(position).acquirableMoney);
                viewHolder.tvMentorPriceBg.setBackgroundResource(R.mipmap.icon_profit_no);
                viewHolder.tvMentorPrice.setTextColor(getResources().getColor(R.color.white));
                viewHolder.tvMentorIsque.setText("(未收取)");
            } else {
                viewHolder.tvMentorPrice.setText(list.get(position).acquirableMoney);
                viewHolder.tvMentorPriceBg.setBackgroundResource(R.mipmap.icon_profit_ok);
                viewHolder.tvMentorPrice.setTextColor(getResources().getColor(R.color.price));
                viewHolder.tvMentorIsque.setText("(已收取)");
            }
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.tv_mentor_name)
            TextView tvMentorName;
            @BindView(R.id.tv_mentor_time)
            TextView tvMentorTime;
            @BindView(R.id.tv_mentor_isque)
            TextView tvMentorIsque;
            @BindView(R.id.tv_mentor_price_bg)
            TextView tvMentorPriceBg;
            @BindView(R.id.tv_mentor_price)
            TextView tvMentorPrice;

            public ViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }
}
